package com.tpvlog.netty;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOutboundHandlerAdapter;
import io.netty.channel.embedded.EmbeddedChannel;

public class ExceptionDemo {
    static class ExceptionInHandler extends ChannelInboundHandlerAdapter {
        private String name;

        ExceptionInHandler(String name) {
            this.name = name;
        }

        @Override
        public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
            System.out.println("ExceptionInHandler[" + name + "]：channelRead");
            throw new RuntimeException("ExceptionInHandler[" + name + "] Error");
        }

        @Override
        public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
            System.out.println("ExceptionInHandler[" + name + "] ERROR!!!!!");
            super.exceptionCaught(ctx, cause);
        }
    }

    static class ExceptionOutHandler extends ChannelOutboundHandlerAdapter {
        private String name;
        ExceptionOutHandler(String name) {
            this.name = name;
        }

        @Override
        public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
            System.out.println("ExceptionOutHandler[" + name + "] ERROR!!!!!");
            super.exceptionCaught(ctx, cause);
        }
    }

    public static void main(String[] args) {
        ChannelInitializer channelInitializer = new ChannelInitializer<EmbeddedChannel>() {
            @Override
            protected void initChannel(EmbeddedChannel ch) throws Exception {
                ch.pipeline()
                        .addLast(new ExceptionInHandler("IN_A"))
                        .addLast(new ExceptionInHandler("IN_B"))
                        .addLast(new ExceptionInHandler("IN_C"));

                ch.pipeline()
                        .addLast(new ExceptionOutHandler("OUT_A"))
                        .addLast(new ExceptionOutHandler("OUT_B"))
                        .addLast(new ExceptionOutHandler("OUT_C"));
            }
        };
        EmbeddedChannel channel = new EmbeddedChannel(channelInitializer);
        ByteBuf buf = Unpooled.buffer();
        buf.writeInt(90);
        channel.writeInbound(buf);
    }
}
